package org.jeecgframework.web.service.impl;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ImageUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.util.FileBean;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by 大伟 on 2016/12/22.
 * Description
 */
@Service("imgCompressService")
public class ImgCompressService {

    private static final Logger logger = Logger.getLogger(ImgCompressService.class);

    private static ExecutorService es = Executors.newFixedThreadPool(3);


    public class Compress implements Runnable {
        FileBean fb = new FileBean();
        Compress(FileBean fb){
            this.fb = fb;
        }
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String resourceFileName = fb.getFileName();
            logger.info("rename file name");
            File sourceFile = new File(fb.getFilePath() + "\\" + fb.getFileName());
            File renameFile = new File(fb.getFilePath() + "\\source-" + fb.getFileName());
            if(sourceFile.exists()){
                sourceFile.renameTo(renameFile);
                logger.info("to:"+sourceFile.getName());
                File compressDest = new File(fb.getFilePath() + "\\"+resourceFileName);
                try{
                    ImageUtils.compress(renameFile, compressDest);
                }catch(Exception e){
                    if(renameFile.exists()){
                        renameFile.renameTo(sourceFile);
                    }
                    if(compressDest.exists()){
                        compressDest.delete();
                    }
                }
            }
        }
    }

    public void startCompress(FileBean fb) {
       es.submit(new Compress(fb));
    }
}
